const WebSocket = require('ws');
const http = require('http');
const express = require('express');
const path = require('path');

const app = express();
const server = http.createServer(app);

// 使用WebSocket服务器依附在HTTP服务器上
const wss = new WebSocket.Server({ server });

wss.on('connection', (socket) => {
    console.log('Client connected');

    // 处理接收到的消息
    socket.on('message', (message) => {
        console.log(`Received: ${message}`);
        console.log(`Type of message: ${typeof message}`);
        console.log(message);
        let text = message
       if (message instanceof Buffer) {
         text = message.toString('utf-8');
       } else if  (typeof message === 'string') {
           text = message
       }
        // 广播消息给所有客户端
        wss.clients.forEach((client) => {
            if (client.readyState === WebSocket.OPEN) {
                client.send(text);
            }
        });
    });

    // 处理断开连接
    socket.on('close', () => {
        console.log('Client disconnected');
    });
});

// 设置静态文件目录（如果有前端页面）
const publicPath = path.join(__dirname, 'public');
app.use(express.static(publicPath));

// 自动提供HTML文件
app.get('/', (req, res) => {
    res.sendFile(path.join(publicPath, 'index.html'));
});

// 启动服务器监听
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
    console.log(`Server is listening on port ${PORT}`);
});
